import { URL, URLSearchParams } from 'url';
import type { H3Event, EventHandlerRequest } from 'h3'

export const listenRequest = (
    event: H3Event<EventHandlerRequest>,
    options:Record<string,Function>
) => {
    // 传递的参数
    const params = getParams(event) || {}
    const callback = options[event.context!.params!._]
    return callback && callback({
        params,
        event,
    })
}
// 获取参数
function getParams(event: H3Event<EventHandlerRequest>):{
    // _: string,
    [key: string] : string | number
} {
    const url = new URL('http://localhost:3000' + event.req.originalUrl);
    const searchParams = new URLSearchParams(url.search);
    return {
        ...event.context.params,
        ...Object.fromEntries(searchParams.entries())
    }
}